<template>
  <div class="sleep-state-chart">
    <div class="chart-container">
      <div ref="chart" class="echarts-chart"></div>
      <div class="chart-overlay">
        <div class="chart-header">
          <h3>睡眠状态分析</h3>
          <div class="chart-controls">
            <label>更新间隔:</label>
            <select v-model="selectedInterval" @change="updateInterval" class="interval-selector">
              <option value="3000">3秒</option>
              <option value="5000">5秒</option>
              <option value="10000">10秒</option>
            </select>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import BrainWaveClient from '../utils/BrainWaveClient.js';

export default {
  name: 'SleepStateChart',
  props: {
    brainWaveClient: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      chart: null,
      states: [], // 存储状态数据: [{time: timestamp, state: 'Awake', confidence: 0.85}]
      timer: null,
      updateInterval: 3000, // 每3秒更新
      selectedInterval: 3000, // 选中的更新间隔
      // 实时脑状态数据
      currentBrainState: {
        state: '正常',
        confidence: 0.0,
        details: {
          delta_ratio: 0,
          theta_ratio: 0,
          alpha_ratio: 0,
          beta_ratio: 0,
          gamma_ratio: 0,
          dominant_band: 'alpha',
          signal_quality: 'unknown'
        }
      },
      // 状态映射（基于brain_state_classification_guide.md）
      stateMapping: {
        // 睡眠相关状态
        'n3_deep_sleep': 'N3深度睡眠',
        'n2_light_sleep': 'N2浅睡眠',
        'n1_light_sleep': 'N1入睡期',
        'rem_sleep': 'REM快速眼动睡眠',
        'eye_movement_stage': '眼动期',
        
        // 清醒认知状态
        'alert': '警觉状态',
        'focused': '专注状态',
        'excited': '兴奋状态',
        
        // 放松和冥想状态
        'relaxed': '放松状态',
        'meditative': '深度冥想',
        'drowsy': '困倦状态',
        
        // 异常状态
        'artifact': '信号异常',
        'unknown': '未知状态',
        
        // 兼容性映射（旧版本支持）
        'relax': '放松状态',
        'focus': '专注状态',
        'meditation': '深度冥想',
        'normal': '警觉状态',
        'deep_sleep': 'N3深度睡眠',
        'light_sleep': 'N2浅睡眠',
        'awake': '警觉状态',
        'wake': '警觉状态'
      }
    };
  },
  mounted() {
    this.initChart();
    this.setupWebSocketHandlers();
    this.startUpdating();
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer);
    if (this.chart) this.chart.dispose();
  },
  watch: {
    // 监听brainWaveClient的变化
    brainWaveClient: {
      handler(newClient) {
        if (newClient) {
          console.log('SleepStateChart: 检测到brainWaveClient变化，重新设置回调');
          this.setupWebSocketHandlers();
        }
      },
      immediate: true // 立即执行一次
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      this.updateChart();
    },
    updateChart() {
      const option = {
        backgroundColor: 'transparent',
        grid: {
          left: '10%',
          right: '10%',
          top: '15%',
          bottom: '15%'
        },
        xAxis: {
          type: 'time',
          axisLine: {
            lineStyle: {
              color: '#87CEEB'
            }
          },
          axisLabel: {
            color: '#4682B4'
          }
        },
        yAxis: {
          type: 'category',
          data: [
            '信号异常',
            'N3深度睡眠', 
            'REM快速眼动睡眠',
            'N2浅睡眠',
            'N1入睡期',
            '眼动期',
            '困倦状态',
            '深度冥想',
            '放松状态',
            '警觉状态',
            '专注状态',
            '兴奋状态',
            '未知状态'
          ],
          axisLine: {
            lineStyle: {
              color: '#87CEEB'
            }
          },
          axisLabel: {
            color: '#4682B4'
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(135, 206, 235, 0.2)'
            }
          }
        },
        series: [{
          name: '睡眠状态',
          type: 'line',
          data: this.states.map(s => [s.time, s.state]),
          lineStyle: {
            color: '#00BFFF',
            width: 3,
            shadowColor: '#00BFFF',
            shadowBlur: 10,
            shadowOffsetY: 2
          },
          itemStyle: {
            color: (params) => {
              // 根据置信度调整颜色透明度
              const confidence = this.states[params.dataIndex]?.confidence || 0.7;
              const alpha = Math.max(0.4, confidence);
              return `rgba(0, 191, 255, ${alpha})`;
            },
            borderColor: '#87CEEB',
            borderWidth: 2,
            shadowColor: '#00BFFF',
            shadowBlur: 8
          },
          emphasis: {
            lineStyle: {
              width: 5,
              shadowBlur: 15
            },
            itemStyle: {
              shadowBlur: 12
            }
          },
          smooth: true,
          symbol: 'circle',
          symbolSize: (value, params) => {
            // 根据置信度调整点的大小
            const confidence = this.states[params.dataIndex]?.confidence || 0.7;
            return 6 + confidence * 6;
          },
          animation: true,
          animationDuration: 1000,
          animationEasing: 'cubicOut'
        }],
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(135, 206, 235, 0.9)',
          borderColor: '#87CEEB',
          textStyle: {
            color: '#fff'
          },
          formatter: (params) => {
            const stateData = this.states[params.dataIndex];
            if (!stateData) return params.name;
            
            const time = new Date(stateData.time).toLocaleTimeString();
            const confidence = (stateData.confidence * 100).toFixed(1);
            const originalState = stateData.originalState || stateData.state;
            
            return `
              <div>
                <strong>时间:</strong> ${time}<br/>
                <strong>状态:</strong> ${stateData.state}<br/>
                <strong>原始状态:</strong> ${originalState}<br/>
                <strong>置信度:</strong> ${confidence}%
              </div>
            `;
          }
        }
      };
      this.chart.setOption(option);
    },
    // 设置WebSocket事件处理器
    setupWebSocketHandlers() {
      console.log('SleepStateChart: 设置WebSocket处理器', this.brainWaveClient);
      if (this.brainWaveClient) {
        console.log('SleepStateChart: brainWaveClient存在，设置onBrainState回调');
        // 设置脑状态分析数据接收回调
        this.brainWaveClient.onBrainState = this.handleBrainState;
        console.log('SleepStateChart: onBrainState回调已设置:', typeof this.brainWaveClient.onBrainState);
      } else {
        console.warn('SleepStateChart: brainWaveClient不存在，无法设置回调');
      }
    },
    
    // 处理接收到的脑状态数据
    handleBrainState(data) {
      console.log('SleepStateChart接收到脑状态数据:', data);
      console.log('data.details:', data.brain_state);
      // 更新当前脑状态
      this.currentBrainState = {
        state: data.brain_state.state || '正常',
        confidence: data.brain_state.confidence || 0.0,
        details: data.brain_state.details.average_ratios || {
          delta_ratio: 0,
          theta_ratio: 0,
          alpha_ratio: 0,
          beta_ratio: 0,
          gamma_ratio: 0,
          dominant_band: 'alpha',
          signal_quality: 'unknown'
        }
      };
      
      console.log('更新后的脑状态:', this.currentBrainState);
      
      // 降低置信度阈值，使更容易显示状态点
      if (this.currentBrainState.confidence > 0.3) {
        console.log('添加状态点到图表，置信度:', this.currentBrainState.confidence);
        this.addStatePoint();
      } else {
        console.log('置信度过低，不添加状态点:', this.currentBrainState.confidence);
      }
    },
    
    // 添加状态点到图表
    addStatePoint() {
      const mappedState = this.stateMapping[this.currentBrainState.state] || '浅睡眠3';
      const newState = {
        time: new Date(),
        state: mappedState,
        confidence: this.currentBrainState.confidence,
        originalState: this.currentBrainState.state,
        details: this.currentBrainState.details
      };
      
      console.log('添加新状态点:', newState);
      
      this.states.push(newState);
      
      // 保持最近50个数据点
      if (this.states.length > 50) {
        this.states.shift();
      }
      
      this.updateChart();
    },
    
    startUpdating() {
      if (this.timer) clearInterval(this.timer);
      // 只在有WebSocket连接时更新，移除模拟数据逻辑
    },
    updateInterval() {
      this.updateInterval = parseInt(this.selectedInterval);
      // 无需重新启动定时器，因为模拟已移除
    }
  }
};
</script>

<style scoped>
.sleep-state-chart {
  width: 100%;
  height: 100%;
  max-height: 45vh;
  margin: 0;
  background: linear-gradient(135deg, #87CEEB 0%, #B0E0E6 50%, #E0F6FF 100%);
  border-radius: 15px;
  padding: 15px;
  box-shadow: 0 8px 32px rgba(135, 206, 235, 0.3);
  color: #4682B4;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.sleep-state-chart::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle at 20% 80%, rgba(0, 191, 255, 0.1) 0%, transparent 50%),
              radial-gradient(circle at 80% 20%, rgba(135, 206, 235, 0.1) 0%, transparent 50%);
  pointer-events: none;
  animation: shimmer 4s ease-in-out infinite alternate;
}



.chart-container {
  width: 100%;
  flex: 1;
  min-height: 350px;
  position: relative;
  overflow: hidden;
  margin: 0;
}

.echarts-chart {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.chart-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 10;
}

.chart-overlay .chart-header {
  position: absolute;
  top: 15px;
  left: 20px;
  right: 20px;
  margin-bottom: 0;
  pointer-events: auto;
  z-index: 11;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.chart-overlay .chart-header h3 {
  margin: 0;
  font-size: 1.2rem;
  color: rgba(255, 255, 255, 0.9);
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  flex: 1;
  text-align: left;
}

.chart-overlay .chart-controls {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(0, 0, 0, 0.6);
  padding: 6px 12px;
  border-radius: 15px;
  backdrop-filter: blur(5px);
}

.chart-overlay .chart-controls label {
  font-size: 0.8rem;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.9);
  white-space: nowrap;
}

.chart-overlay .interval-selector {
  padding: 4px 8px;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.9);
  color: #4682B4;
  font-size: 0.8rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.chart-overlay .interval-selector:hover {
  border-color: rgba(255, 255, 255, 0.6);
  background: rgba(255, 255, 255, 1);
}

.chart-overlay .interval-selector:focus {
  outline: none;
  border-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
}

@keyframes shimmer {
  0% {
    opacity: 0.5;
  }
  100% {
    opacity: 0.8;
  }
}
</style>